package main

// 无缓冲区 channel：用于替代锁机制，实现“不通过共享内存来通信”
// 示例： 实现一个计数器，实现多个 worker goroutine 安全修改计数器变量

import (
	"log"
	"sync"
)

type Counter struct {
	ch chan int
	i  int
}

func NewCounter() *Counter {
	cter := &Counter{
		ch: make(chan int),
	}

	go func() {
		for {
			cter.i++          // 计数器递增
			cter.ch <- cter.i // 将值发送到 channel
		}
	}()

	return cter
}

func (cter *Counter) Increase() int {
	return <-cter.ch
}

func main() {
	cter := NewCounter()

	var wg sync.WaitGroup

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(n int) {
			val := cter.Increase()
			log.Printf("GorouintId-%d, current value is:%d\n", n, val)
			wg.Done()
		}(i)
	}

	wg.Wait()

}
